package com.fling.abcde.base;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.fling.abcde.R;
import com.lib.okhttp.NetURL;
import com.lib.common.bean.BaseResp;
import com.lib.utils.FileUtils;
import com.lib.utils.ImageUtils;
import com.lib.utils.XLog;

import java.io.File;

public class BaseWebActivity extends BaseActivity {

    private static final int CAPTURE = 0x1;
    private static final int SELECT = 0x2;

    public static final String URL_DATA = "url";
    public static final String IS_NEED_BASE_URL = "isNeedBaseUrl";

    public boolean mDisableBack;
    protected WebView mWebView;
    private LinearLayout mErrHintLayer;
    private View mProgress;
    private String mUrl;
    private boolean mAccessWebErr;
    private AlertDialog mCameraDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setActionBarVisible(false);
        setContentView(R.layout.activity_base_web);
        initIntent(getIntent());
        initView();
        settings();
        XLog.i(mUrl);
        mWebView.loadUrl(mUrl);
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        initIntent(intent);
    }

    private void initIntent(Intent intent) {

        mUrl = intent.getStringExtra(URL_DATA);
        if (mUrl == null || mUrl.equals("")) {
            mUrl = "http://www.baidu.com";
            return;
        }
        if (intent.getBooleanExtra(IS_NEED_BASE_URL, true)) {
            mUrl = NetURL.BASE_URL + mUrl;
        }
    }

    private void initView() {

        mErrHintLayer = findViewById(R.id.baseWeb_webView_Err_hint);
        mProgress = findViewById(R.id.baseWeb_progress);
        mWebView = findViewById(R.id.baseWeb_webView);
        mErrHintLayer.setOnClickListener(v -> {
            mWebView.reload();
        });
        showLoading();
        // mNetManager.doOnlyTokenRequest(TaskId.GET_USER_INFO, NetURL.GET_USER_INFO, UserBean.class);
    }

    @Override
    public void onDataChanged(BaseResp baseResp) {

        super.onDataChanged(baseResp);
        switch (0) {
            case 1:
                if (baseResp.getCode() == 200) {

                }
                break;
            case 2:
                if (baseResp.getCode() == 200) {

                }
                break;
        }
    }

    @Override
    public void onResume() {

        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }
    }

    private void settings() {

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        // settings.setSupportZoom(true);
        // settings.setDisplayZoomControls(true);

        settings.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= 16) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        settings.setAppCacheEnabled(true);
        XLog.i(getCacheDir().getAbsolutePath() + "/webview_cache");
        settings.setAppCachePath(getCacheDir().getAbsolutePath() + "/webview_cache");
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        // settings.setGeolocationEnabled(true);
        // /**
        //  用WebView显示图片，可使用这个参数 设置网页布局类型：
        //  1、LayoutAlgorithm.NARROW_COLUMNS ：适应内容大小
        //  2、LayoutAlgorithm.SINGLE_COLUMN : 适应屏幕，内容将自动缩放
        //  */
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // settings.setUseWideViewPort(true);
        // settings.setLoadWithOverviewMode(true);
        // mWebView.requestFocus();

        // if (Build.VERSION.SDK_INT >= 19) {
        // 	mWebView.getSettings().setLoadsImagesAutomatically(true);
        // } else {
        // 	mWebView.getSettings().setLoadsImagesAutomatically(false);
        // }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int progress) {

                // super.onProgressChanged(view, progress);
                // mProgress.setLayoutParams(new FrameLayout.LayoutParams(
                // 	(int) (progress / 100f * getResources().getDisplayMetrics().widthPixels),
                // 	ConvertUtils.dp2px(BaseApplication.sContext, 2)));
            }

        });
        mWebView.setWebViewClient(new WebViewClient() {

            // @Override
            // public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            //
            // 	if (url.contains("===")) {
            // 		String action = url.split("===")[1];
            // 		LogUtils.i("666 拦截1-->", url);
            // 		if ("back".equals(action)) {
            // 			onBackPressed();
            // 		} else if ("clear".equals(action)) {
            // 			mWebView.clearHistory();
            // 		} else {
            // 			WebViewIntercept.handleInterceptUrl(action);
            // 		}
            // 		return null;
            // 	}
            // 	return super.shouldInterceptRequest(view, url);
            // }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.contains("tel:")) {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                    startActivity(intent);
                    return true;
                }

                if (url.contains("action===")) {
                    String action = url.split("action===")[1];

                    if ("photo".equals(action)) {
                        //上传图片
                        uploadFile();
                        return true;
                    }

                    WebViewIntercept.handleInterceptUrl(BaseWebActivity.this, mWebView, action);
                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                hideLoading();
                mAccessWebErr = true;
            }

            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

                hideLoading();
                mProgress.setVisibility(View.GONE);
                handler.proceed();
                mAccessWebErr = true;
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                showLoading();
                // mProgress.setVisibility(View.VISIBLE);
            }

            public void onPageFinished(WebView view, String url) {

                hideLoading();
                // mProgress.setVisibility(View.GONE);

                if (mAccessWebErr) {
                    mAccessWebErr = false;
                    mErrHintLayer.setVisibility(View.VISIBLE);
                } else {
                    mErrHintLayer.setVisibility(View.GONE);
                    if (url.contains("/h5/Set/index")) {
                        File file = getCacheDir().getAbsoluteFile();
                        XLog.i(file.getName());
                        mWebView.loadUrl("javascript:showcache('" +
                                FileUtils.formatFileSize(FileUtils.getFolderSize(file)) + "')");
                    }
                }
            }
        });
    }

    private void uploadFile() {

        if (mCameraDialog == null) {
            mCameraDialog = new AlertDialog.Builder(this)
                    .setItems(new String[] {"拍照上传", "手机相册"}, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            switch (which) {
                                case 0:
                                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                    startActivityForResult(intent, CAPTURE);
                                    break;
                                case 1:
                                    Intent in = new Intent(Intent.ACTION_PICK);
                                    in.setType("image/*");
                                    startActivityForResult(in, SELECT);
                                    break;
                            }
                        }
                    }).create();
        }
        mCameraDialog.show();
    }

    private void saveAndUpload(Bitmap photo) {

        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(getCacheDir(), fileName);
        ImageUtils.save(photo, file, Bitmap.CompressFormat.PNG, false);
        showLoading();
//        mNetManager.uploadFile(null, "", file, NetManager.MEDIA_TYPE_IMG, URLBean.class);
    }

    @Override
    protected void onPause() {

        if (mWebView != null) {
            mWebView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onBackPressed() {

        if (mDisableBack) {
            Toast.makeText(this, "当前页面,不允许返回!", Toast.LENGTH_SHORT).show();
        } else if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        // if (mWebView != null) {
        // 	mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        // 	mWebView.clearHistory();
        // 	mWebView.removeAllViews();
        // 	((ViewGroup) mWebView.getParent()).removeAllViews();
        // 	mWebView.destroy();
        // 	mWebView = null;
        // }
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}